<script setup lang="ts">
import { CloseOutlined, FullscreenOutlined, UnorderedListOutlined } from '@ant-design/icons-vue';
import { Button, Drawer, Pagination } from 'ant-design-vue';
import { computed, defineEmits, defineProps, onBeforeUnmount, onMounted, ref, watch } from 'vue';
// 定义 props
const props = defineProps<{
  isFullscreen: boolean;
  sections: Array<{ id: string; content: string; title: string }>;
  loading: boolean;
}>();

// 定义 emit 函数
const emit = defineEmits<{
  (e: 'linkClick', url: string): void;
  (e: 'close'): void; // 用于触发关闭当前Tab的事件
  (e: 'toggleFullscreen'): void; // 用于切换全屏状态
}>();

// 当前页和内容
const currentPage = ref(1);
// 使用 computed 计算总章节数
const totalSections = computed(() => props.sections.length);

// 修改当前内容的计算逻辑
const currentContent = computed(() => {
  if (props.loading)
    return '加载中...';
  if (props.sections.length === 0)
    return '暂无内容';
  return props.sections[currentPage.value - 1]?.content || '内容不存在';
});
// 控制 Drawer 显示隐藏
const showToc = ref(false);
const toggleToc = () => {
  showToc.value = !showToc.value;
};

// 处理页面变化
const handlePageChange = (page: number) => {
  currentPage.value = page;
  // // 直接使用 props.sections
  // if (props.sections[page - 1])
  //   currentContent.value = props.sections[page - 1].content;
  // else
  //   currentContent.value = '内容不存在';
};

// 跳转到指定章节
const goToSection = (sectionId: string) => {
  // 直接使用 props.sections
  const pageIndex = props.sections.findIndex(section => section.id === sectionId);
  if (pageIndex !== -1) {
    currentPage.value = pageIndex + 1; // 页码从1开始
    // currentContent.value = props.sections[pageIndex].content;
    showToc.value = false; // 关闭目录 Drawer
  }
};

// 链接点击处理函数
const handleLinkClick = (e: Event) => {
  const target = e.target as HTMLElement;

  // 查找包含 data-href 属性的祖先元素，直到 .side-manual
  let currentElement: HTMLElement | null = target;
  while (currentElement && currentElement !== e.currentTarget) {
    if (currentElement.tagName.toLowerCase() === 'a') {
      e.preventDefault(); // 阻止默认行为
      const href = currentElement.getAttribute('data-href');
      if (href) {
        emit('linkClick', href);
        break;
      }
    }
    currentElement = currentElement.parentElement;
  }
};

// 全屏按钮逻辑
const toggleFullscreen = () => {
  emit('toggleFullscreen'); // 通知父组件切换全屏状态
};

// 关闭按钮逻辑
const closeTab = () => {
  emit('close'); // 通知父组件关闭当前Tab（等同于再次点击tabs）
};

onMounted(() => {
  // 添加事件监听器到整个组件
  const sideManual = document.querySelector('.side-manual');
  if (sideManual)
    sideManual.addEventListener('click', handleLinkClick);

  // 在全屏状态下，默认展开目录
  if (props.isFullscreen)
    showToc.value = true;
});

// 监听 isFullscreen 的变化
watch(() => props.isFullscreen, (newVal) => {
  if (newVal) {
    // 进入全屏，展开目录
    showToc.value = true;
  }
  else {
    // 退出全屏，关闭目录
    showToc.value = false;
  }
});

onBeforeUnmount(() => {
  // 移除事件监听器
  const sideManual = document.querySelector('.side-manual');
  if (sideManual)
    sideManual.removeEventListener('click', handleLinkClick);
});
</script>

<template>
  <div class="side-manual" :class="{ fullscreen: props.isFullscreen }">
    <div class="toolbar">
      <Button @click="toggleFullscreen">
        <FullscreenOutlined />
        {{ props.isFullscreen ? '退出全屏' : '全屏' }}
      </Button>
      <Button @click="closeTab">
        <CloseOutlined />
        关闭
      </Button>
    </div>

    <!-- 全屏模式下的主内容区域 -->
    <div v-if="props.isFullscreen" class="main-content">
      <!-- 左侧目录 -->
      <div class="toc-container">
        <ul class="table-of-contents">
          <li v-for="section in sections" :key="section.id">
            <a href="javascript:void(0)" @click="goToSection(section.id)">
              {{ section.title || `章节 ${section.id}` }}
            </a>
          </li>
        </ul>
      </div>
      <!-- 右侧内容展示区域 -->
      <div class="content-wrapper">
        <div class="fixed-width-container">
          <div
            class="content-display"
            v-html="currentContent"
          />
          <Pagination
            class="pagination"
            :current="currentPage"
            :total="totalSections"
            :page-size="1"
            :show-quick-jumper="true"
            style="text-align: center; margin-bottom: 1.25rem;"
            @change="handlePageChange"
          />
        </div>
      </div>
    </div>

    <!-- 非全屏模式下的内容和目录按钮 -->
    <div v-else class="content-wrapper">
      <div
        class="content-display"
        v-html="currentContent"
      />

      <div class="fixed-footer">
        <button class="toc-button" @click="toggleToc">
          <UnorderedListOutlined /> 目录
        </button>

        <Pagination
          class="pagination"
          :current="currentPage"
          :total="totalSections"
          :page-size="1"
          :show-quick-jumper="true"
          @change="handlePageChange"
        />
      </div>

      <Drawer
        title="目录"
        :visible="showToc"
        placement="left"
        :get-container="false"
        @close="toggleToc"
      >
        <ul class="table-of-contents">
          <li v-for="section in sections" :key="section.id">
            <a href="javascript:void(0)" @click="goToSection(section.id)">
              {{ section.title || `章节 ${section.id}` }}
            </a>
          </li>
        </ul>
      </Drawer>
    </div>
  </div>
</template>

<style scoped>
.side-manual {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.side-manual.fullscreen {
  padding: 0;
}

.toolbar {
  display: flex;
  justify-content: flex-end;
  gap: 0.625rem;
  padding: 0.625rem;
  background-color: #fff;
  border-bottom: 0.0625rem solid #ddd;
  height: 3.75rem;
  align-items: center;
}

.main-content {
  flex: 1;
  display: flex;
  overflow: hidden;
}

.toc-container {
  width: 12.5rem;
  background-color: #f9f9f9;
  border-right: 0.0625rem solid #ddd;
  padding: 1.25rem;
  overflow-y: auto;
}

.fixed-width-container {
  width: 98.9375rem;
  margin: 0 auto;
  display: flex;
  flex-direction: column;
  height: 100%;
}

.content-wrapper {
  flex: 1;
  position: relative;
  display: flex;
  flex-direction: column;
  height: 100%;
  position: relative;
  overflow: hidden; /* 防止出现两个滚动条 */
}

.content-display {
  flex: 1;
  padding: 1.25rem;
  overflow-y: auto;
  /* 移除之前的 height 和 padding-bottom */
  margin-bottom: 3.75rem; /* 为 fixed-footer 留出空间 */
}
.content-display ::v-deep img {
  max-width: 100%;
  height: auto;
  display: block;
  margin: 0 auto;
}

.fixed-footer {
  position: absolute; /* 改为 absolute 定位 */
  bottom: 0;
  left: 0;
  right: 0; /* 添加 right: 0 确保宽度自适应 */
  height: 3.75rem;
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 0.625rem 1.25rem;
  background-color: #ffffff;
  border-top: 0.0625rem solid #ddd;
  z-index: 1000;
}

.fixed-footer .toc-button {
  position: absolute;
  left: 0.625rem;
  background-color: transparent;
  border: none;
  cursor: pointer;
  font-size: 1rem;
  display: flex;
  align-items: center;
}

.fixed-footer .toc-button:hover {
  color: #0056b3;
}

.fixed-footer .pagination {
  flex: 1;
  text-align: center;
  margin-left: 2.5rem;
}

.table-of-contents {
  list-style-type: none;
  padding: 0;
}

.table-of-contents li {
  margin: 0.625rem 0;
}

.table-of-contents a {
  color: #007bff;
  text-decoration: none;
}

.table-of-contents a:hover {
  text-decoration: underline;
}

.external-link {
  color: #007bff;
  text-decoration: underline;
  cursor: pointer;
}

.external-link:hover {
  text-decoration: none;
}
</style>
